#!/bin/bash
TOMCAT_PATH='/home/linux_7220765221/tomcat9'
EXAM_PATH='/home/linux_7220765221/Exam'

# 获取 Tomcat servlet-api.jar 作为基础类路径
CP="${TOMCAT_PATH}/lib/servlet-api.jar"

# 步骤 1: 获取 webapps/ROOT/WEB-INF/lib 目录下的所有 JAR 文件并添加到 CP 中
for jar in ${TOMCAT_PATH}/webapps/ROOT/WEB-INF/lib/*.jar; do
    CP="${CP}:$jar"
done

# 输出最终的类路径（可以调试时使用）
echo "Classpath: $CP"

# 步骤 2: 编译 Java 文件
SOURCE_DIR="${EXAM_PATH}/code"
TARGET_DIR="${EXAM_PATH}/target"
mkdir -p "$TARGET_DIR"

# 查找所有 Java 源文件
JAVA_FILES=$(find $SOURCE_DIR -name "*.java")

if [ -z "$JAVA_FILES" ]; then
    echo "No Java files found in $SOURCE_DIR"
    exit 1
fi

# 使用 javac 编译 Java 文件
javac -cp "$CP" -d "$TARGET_DIR" $JAVA_FILES

# 检查编译是否成功
if [ $? -ne 0 ]; then
    echo "Compilation failed!"
    exit 1
fi

# 步骤 3: 部署：将编译好的 .class 文件复制到 Tomcat 的 classes 目录中
TARGET_CLASSES_DIR="${TOMCAT_PATH}/webapps/ROOT/WEB-INF/classes/com/jiang/servlets"
echo "Copying class files to $TARGET_CLASSES_DIR"

#cp  ${TARGET_DIR}/*.class ${TARGET_CLASSES_DIR}/

# 步骤 4: 重启 Tomcat
echo "Shutting down Tomcat..."
cd ${TOMCAT_PATH}/bin
./shutdown.sh

# 等待 3 秒钟
echo "Waiting for 3 seconds before restarting Tomcat..."
sleep 3

echo "Starting Tomcat..."
./startup.sh

echo "Deployment and Tomcat restart complete!"

